import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Table,
  Card,
  Row,
  Col,
  Input,
  InputNumber,
  Button,
  Select,
  Badge,
  Divider,
  Modal,
  Tooltip,
} from 'antd';

import '@ant-design/compatible/assets/index.css';
import { TableListData } from './data';

const { Option } = Select;
const { TextArea } = Input;
const { pathname } = window.location;
const { Item } = Form;

const status_keys = ['', 'error', 'warning', 'success'];
const status_values = ['', '待确认', '已修改', '已确认'];

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  location: { search: any };
  loading: boolean;
  datalist: TableListData;
  partnersList: any;
  screen: string;
}

interface TableListState {
  searchValues: any;
  pageNum: number;
  numPerPage: number;
  visible: boolean;
  updateValues: {
    id: number | string;
    real_amount: number | string;
    amount_reason: number | string;
  };
  modalShow: boolean;
  statement_id: number | string;
  user_type: string;
  rowId:number;
}

function mapStateToProps(state: any) {
  const {
    statementsList: { datalist, partnersList },
    global: { screen },
    loading,
  } = state;

  return {
    datalist,
    partnersList,
    screen,
    loading: loading.effects['statementsList/fetch'],
  };
}

@connect(mapStateToProps)
class TableList extends Component<TableListProps, TableListState> {
  timer: any = null;

  columns: any = [
    {
      title: '合作商名称',
      dataIndex: 'franchise_name',
      width: 120,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit nameLink"
            onClick={() => this.handleShowStatement(record.id, record.franchise_name)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 200,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '发起时间',
      dataIndex: 'create_time',
      width: 200,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 90,
      render: (value: string) => <Badge status={status_keys[value]} text={status_values[value]} />,
    },
    {
      title: '应结金额(元)',
      dataIndex: 'origin_amount_desc',
      width: 120,
    },
    {
      title: '实结金额(元)',
      dataIndex: 'real_amount_desc',
      width: 120,
    },
    {
      title: '合作商对账人',
      dataIndex: 'confirm_name',
      width: 120,
      render: (text: string) => text || '--',
    },
    {
      title: '操作',
      width: 150,
      fixed: 'right',
      render: (text: any, record: any) => {
        const { user_type } = this.state;
        return (
          <div>
            <span
              className={record.status === 1 && user_type === 'inner'
                ? 'operLink'
                : 'operLinkDisabled'}
              onClick={() => this.handleShowModal(record)}
            >
              修改
            </span>
            <Divider type="vertical" />
            <span
              className={record.status !== 3 && user_type === 'franchisee'
                ? 'operLink'
                : 'operLinkDisabled'}
              onClick={() => this.handleShowConfirm(true, record)}
            >
              确认
            </span>
            <Divider type="vertical" />
            <span
              onClick={() => this.handleShowStatement(record.id, record.franchise_name)}
              className="operLink"
            >
              详情
            </span>
          </div>
        );
      },
    },
  ];

  state: TableListState = {
    searchValues: {},
    pageNum: 1,
    numPerPage: 20,
    visible: false,
    updateValues: {
      id: '',
      real_amount: 0,
      amount_reason: '',
    },
    modalShow: false,
    statement_id: '',
    user_type: '',
    rowId: 0,
  };

  static getDerivedStateFromProps(props: TableListProps, state: TableListState) {
    const { user_type } = state;
    const { datalist, location: { search } } = props;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { page, psize, ...searchValues } = query;

    if (datalist.user_type && user_type !== datalist.user_type) {
      return {
        user_type: datalist.user_type,
      };
    }
    return {
      searchValues,
      pageNum: Number(page) || 1,
      numPerPage: Number(psize) || (props.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    const { datalist } = this.props;
    if (datalist?.list?.length) return;

    this.fetchAction('getPartners', { name: '' });
    this.fetchTableDataList();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageNum, numPerPage } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageNum !== prevState.pageNum
      || numPerPage !== prevState.numPerPage
    ) {
      this.setFieldsValue();
      this.fetchTableDataList();
    }
  }

  // 设置表单值
  setFieldsValue = () => {
    const { searchValues } = this.state;
    const { form: { setFieldsValue } } = this.props;

    setFieldsValue(searchValues);
  };

  // 获取数据
  fetchTableDataList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'statementsList/fetch',
      payload: this.getQueryParams(),
    });
  };

  // 获取查询参数
  getQueryParams = () => {
    const {
      searchValues: { franchise, ...params },
      pageNum,
      numPerPage,
    } = this.state;

    params['franchise.name'] = franchise && franchise.label;
    params['franchise.id'] = franchise && franchise.key;
    params.pageNum = pageNum;
    params.numPerPage = numPerPage;

    return params;
  };

  handleShowConfirm = (modalShow: boolean, record?: any) => {
    this.setState({ modalShow, statement_id: record ? record.id : '' });
  };

  handleConfirm = () => {
    const { searchValues: search, statement_id } = this.state;
    const params = { search, statement_id };
    this.fetchAction('confirm', params);
    this.handleShowConfirm(false);
  };

  handleShowModal = (record: any) => {
    this.setState({
      updateValues: {
        id: record.id,
        real_amount: record.real_amount_desc,
        amount_reason: '',
      },
      visible: true,
    });
  };

  handleSubmit = () => {
    const { form: { validateFields, getFieldsValue } } = this.props;
    validateFields((errors: any, values: any) => {
      if (errors) return;

      const { searchValues: search, updateValues } = this.state;
      const newValues = getFieldsValue(['real_amount', 'amount_reason']);
      const new_updateValues = { ...updateValues, ...newValues };

      this.setState({ updateValues: new_updateValues }, () => {
        const params = { search, ...new_updateValues };
        this.fetchAction('updateMoney', params);
        this.handleCancel();
      });
    });
  };

  handleCancel = () => this.setState({ visible: false });

  handleShowStatement = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${name}`,
      url: `/partner/partnersStatements/list/detail?id=${id}`,
    });
  };

  handlePartners = (name: string) => {
    clearTimeout(this.timer);

    this.timer = setTimeout(() => {
      this.fetchAction('getPartners', { name });
    }, 500);
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields(['title', 'franchise', 'status'], (errors, values) => {
      if (!errors) {
        const query = {
          ...values,
          pageNum: 1,
          numPerPage: 20,
        };

        const { dispatch } = this.props;
        addTab(dispatch, {
          name: '合作商结算单管理',
          url: `${pathname}?${qs.stringify(query)}`,
          isTopMenu: true,
        });
      }
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '合作商结算单管理',
      url: pathname,
      isTopMenu: true,
    });
  };

  fetchAction = (typeName: string, params = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: `statementsList/${typeName}`,
      payload: params,
    });
  };

  handlePerPage = (page: number, psize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, page, psize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '合作商结算单管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  renderSearchFormElem = () => {
    const {
      form: { getFieldDecorator },
      partnersList,
    } = this.props;

    return (
      <Form
        hideRequiredMark
        onSubmit={this.handleSearch}
        className="tableListForm"
      >
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <Item label="合作商名称" colon={false}>
              {getFieldDecorator('franchise')(
                <Select
                  showSearch
                  allowClear
                  placeholder="请选择"
                  labelInValue
                  onSearch={this.handlePartners}
                  filterOption={(input: any, option: any) => option.props.children
                    .toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {partnersList.map((item: any) => (
                    <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                  ))}
                </Select>,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="　　　标题" colon={false}>
              {getFieldDecorator('title')(
                <Input allowClear placeholder="请输入" />,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="　　　状态" colon={false}>
              {getFieldDecorator('status')(
                <Select placeholder="请输入">
                  <Option value="1">待确认</Option>
                  <Option value="2">已修改</Option>
                  <Option value="3">已确认</Option>
                </Select>,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <div className="flexFeView">
              <Button
                type="primary"
                htmlType="submit"
                className="smallButton"
              >
                查询
              </Button>
              <Button
                className="addButton smallButton marginL16"
                type="primary"
                onClick={this.handleReset}
              >
                重置
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  render() {
    const {
      pageNum,
      numPerPage,
      visible,
      modalShow,
      updateValues: { real_amount, amount_reason },
    } = this.state;

    const {
      datalist,
      loading,
      screen,
      form: { getFieldDecorator },
    } = this.props;

    const pagination: object = datalist
      ? {
        total: datalist ? datalist.count : 0,
        pageSize: numPerPage,
        current: pageNum,
        onChange: this.handlePerPage,
        showTotal: () => `共${datalist.count || 0}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        onShowSizeChange: this.handlePerPage,
        showQuickJumper: true,
      }
      : {};

    if (screen === 'sm' || screen === 'lg') {
      delete this.columns[this.columns.length - 1].fixed;
    } else if (screen === 'md') {
      this.columns[this.columns.length - 1].fixed = 'right';
    }

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          {this.renderSearchFormElem()}
        </Card>

        <Card bordered={false} className="tableList">
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableheight60"
            loading={loading}
            columns={this.columns}
            dataSource={datalist.list || []}
            pagination={pagination}
            scroll={{ x: 1200 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <Modal
          title="修改金额"
          visible={visible}
          okText="修改"
          onOk={this.handleSubmit}
          onCancel={this.handleCancel}
        >
          <Form hideRequiredMark className="tableListForm">
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col span={20} offset={2}>
                <Item label="修改金额">
                  {getFieldDecorator('real_amount', {
                    initialValue: real_amount,
                    rules: [{ required: true, message: '请输入修改金额' }],
                  })(
                    <InputNumber placeholder="请输入" style={{ width: '100%' }} />,
                  )}
                </Item>
              </Col>
              <Col span={20} offset={2}>
                <Item label="修改说明">
                  {getFieldDecorator('amount_reason', {
                    initialValue: amount_reason,
                    rules: [{ required: true, message: '请输入修改说明' }],
                  })(
                    <TextArea placeholder="请输入" />,
                  )}
                </Item>
              </Col>
            </Row>
          </Form>
        </Modal>

        <Modal
          title="确认修改"
          visible={modalShow}
          onOk={this.handleConfirm}
          onCancel={() => this.handleShowConfirm(false)}
        >
          <p>是否确认此修改？</p>
        </Modal>

      </Fragment>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
